package com.jsh.erp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.datasource.entities.Contract;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.ContractMapper;
import com.jsh.erp.service.contract.ContractComponent;
import com.jsh.erp.service.contract.ContractService;
import com.jsh.erp.service.project.ProjectService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.service.userBusiness.UserBusinessService;
import com.jsh.erp.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jsh.erp.utils.ResponseJsonUtil.returnJson;

/**
 * @author ji|sheng|hua 华夏erp
 */
@RestController
@RequestMapping(value = "/contract")
@Api(tags = {"合同管理"})
public class ContractController {
    private Logger logger = LoggerFactory.getLogger(ContractController.class);

    @Resource
    private ContractService contractService;
    @Resource
    private ProjectService projectService;
    @Resource
    private SupplierService supplierService;
    @Resource
    private ContractComponent contractComponent;

    @Resource
    private UserBusinessService userBusinessService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserService userService;

    @GetMapping(value = "/table-list")
    @ApiOperation(value = "获取信息列表")
    public String getList(@RequestParam(value = Constants.PAGE_SIZE, required = false) Integer pageSize,
                          @RequestParam(value = Constants.CURRENT_PAGE, required = false) Integer currentPage,
                          @RequestParam(value = Constants.SEARCH, required = false) String search,
                          HttpServletRequest request)throws Exception {
        Map<String, String> parameterMap = ParamUtils.requestToMap(request);
        parameterMap.put(Constants.SEARCH, search);
        Map<String, Object> objectMap = new HashMap<String, Object>();
        if (pageSize != null && pageSize <= 0) {
            pageSize = 10;
        }
        String offset = ParamUtils.getPageOffset(currentPage, pageSize);
        if (StringUtil.isNotEmpty(offset)) {
            parameterMap.put(Constants.OFFSET, offset);
        }
        List<Contract> list = (List<Contract>) contractComponent.select(parameterMap);
        List<JSONObject> jsonList = Lists.newArrayList();
        for (Contract contract : list) {
            JSONObject contactJson = (JSONObject) JSONObject.toJSON(contract);
            if (StringUtils.isNotEmpty(contract.getProjectId()) ) {
                contactJson.put("projectName", projectService.getProject(Long.parseLong(contract.getProjectId())).getName());
            }
            if (StringUtils.isNotEmpty(contract.getSupplierId())) {
                contactJson.put("supplierName", supplierService.getSupplier(Long.parseLong(contract.getSupplierId())).getSupplier());
            }
            jsonList.add(contactJson);
        }
        if (list != null) {
            objectMap.put("total", contractComponent.counts(parameterMap));
            objectMap.put("rows", jsonList);
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            objectMap.put("total", BusinessConstants.DEFAULT_LIST_NULL_NUMBER);
            objectMap.put("rows", new ArrayList<Object>());
            return returnJson(objectMap, "查找不到数据", ErpInfo.OK.code);
        }
    }

    @GetMapping(value = "/checkIsNameAndTypeExist")
    @ApiOperation(value = "检查名称和类型是否存在")
    public String checkIsNameAndTypeExist(@RequestParam Long id,
                                          @RequestParam(value ="name", required = false) String name,
                                          @RequestParam(value ="type") String type,
                                          HttpServletRequest request)throws Exception {
        Map<String, Object> objectMap = new HashMap<>();
        int exist = contractService.checkIsNameAndTypeExist(id, name, type);
        if(exist > 0) {
            objectMap.put("status", true);
        } else {
            objectMap.put("status", false);
        }
        return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
    }

    /**
     * 查找合同信息-下拉框
     * @param request
     * @return
     */
    @PostMapping(value = "/findBySelect")
    @ApiOperation(value = "查找合同信息")
    public JSONArray findBySelectCus(HttpServletRequest request) {
        JSONArray arr = new JSONArray();
        try {
            String type = "UserCustomer";
            Long userId = userService.getUserId(request);
            //获取权限信息
            String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId.toString());
            List<Contract> contractList = contractService.findBySelect();
            JSONArray dataArray = new JSONArray();
            if (null != contractList) {
                boolean customerFlag = systemConfigService.getCustomerFlag();
                for (Contract contract : contractList) {
                    JSONObject item = new JSONObject();
                    Boolean flag = ubValue.contains("[" + contract.getId().toString() + "]");
                    if (!customerFlag || flag) {
                        item.put("id", contract.getId());
                        item.put("name", contract.getName()); //合同名称
                        dataArray.add(item);
                    }
                }
            }
            arr = dataArray;
        } catch(Exception e){
            e.printStackTrace();
        }
        return arr;
    }

    /**
     * 批量设置状态-启用或者禁用
     * @param jsonObject
     * @param request
     * @return
     */
    @PostMapping(value = "/batchSetStatus")
    @ApiOperation(value = "批量设置状态")
    public String batchSetStatus(@RequestBody JSONObject jsonObject,
                                 HttpServletRequest request)throws Exception {
        Boolean status = jsonObject.getBoolean("status");
        String ids = jsonObject.getString("ids");
        Map<String, Object> objectMap = new HashMap<>();
        int res = contractService.batchSetStatus(status, ids);
        if(res > 0) {
            return returnJson(objectMap, ErpInfo.OK.name, ErpInfo.OK.code);
        } else {
            return returnJson(objectMap, ErpInfo.ERROR.name, ErpInfo.ERROR.code);
        }
    }

    @PostMapping(value = "/findBySelectContract")
    @ApiOperation(value = "查找合同信息")
    public JSONArray findBySelectContract(HttpServletRequest request) {
        JSONArray arr = new JSONArray();
        try {
            String type = "Contract";
            Long userId = userService.getUserId(request);
            //获取权限信息
            String ubValue = userBusinessService.getUBValueByTypeAndKeyId(type, userId.toString());
            List<Contract> contractList = contractService.findBySelect();
            JSONArray dataArray = new JSONArray();
            if (null != contractList) {
                boolean customerFlag = systemConfigService.getCustomerFlag();
                for (Contract contract : contractList) {
                    JSONObject item = new JSONObject();
                    Boolean flag = ubValue.contains("[" + contract.getId().toString() + "]");
                    if (!customerFlag || flag) {
                        item.put("id", contract.getId());
                        item.put("name", contract.getName());
                        item.put("sn", contract.getSn());
                        dataArray.add(item);
                    }
                }
            }
            arr = dataArray;
        } catch(Exception e){
            e.printStackTrace();
        }
        return arr;
    }

}
